package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.controller.SetmealController;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author 宋
 * @since 2022-06-06
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;


    /**
     * //判断是否被其他表关联  用被关联的id去其他表里查
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        // 1 . 判断菜品表
        LambdaQueryWrapper<Dish> queryWrapperDish = new LambdaQueryWrapper<>();
        queryWrapperDish.eq(Dish::getCategoryId, id);
        int countDish = dishService.count(queryWrapperDish);
        //判断菜品表里有多少道菜关联了这个菜品分类  >0说明有菜品关联了这个分类 就不能删除
        if (countDish > 0) {
            //已经关联菜品，抛出一个业务异常
            throw new CustomException("当前分类被其他菜品关联了,不能删除");
        }

        // 2 . 判断套餐表
        LambdaQueryWrapper<Setmeal> queryWrapperSetmeal = new LambdaQueryWrapper<>();
        queryWrapperSetmeal.eq(Setmeal::getCategoryId, id);
        int countSetmeal = setmealService.count(queryWrapperSetmeal);
        //判断菜品表里有多少道菜关联了这个菜品分类  >0说明有菜品关联了这个分类 就不能删除
        if (countSetmeal > 0) {
            //已经关联菜品，抛出一个业务异常
            throw new CustomException("当前分类被其他套餐关联了,不能删除");
        }
        // 3 . 走到这说明没有被关联  --> 正常删除
        removeById(id);
    }


}
